package com.guducat.collegeWeb.mapper;

import com.guducat.collegeWeb.entity.User;
import org.apache.ibatis.annotations.*;

/**
 * 用户数据访问接口
 * 使用MyBatis注解方式实现SQL映射
 */
@Mapper
public interface UserMapper {

    /**
     * 根据用户名查询用户
     * @param username 用户名
     * @return 用户对象
     */
    @Results(id = "userResultMap", value = {
        @Result(property = "id", column = "id", id = true),
        @Result(property = "username", column = "username"),
        @Result(property = "password", column = "password"),
        @Result(property = "nickname", column = "nickname"),
        @Result(property = "avatar", column = "avatar"),
        @Result(property = "permission", column = "permission"),
        @Result(property = "status", column = "status"),
        @Result(property = "createTime", column = "create_time"),
        @Result(property = "updateTime", column = "update_time"),
        @Result(property = "lastLoginIp", column = "last_login_ip")
    })
    @Select("SELECT * FROM user WHERE username = #{username} AND status = 1")
    User findByUsername(@Param("username") String username);

    /**
     * 根据ID查询用户
     * @param id 用户ID
     * @return 用户对象
     */
    @ResultMap("userResultMap")
    @Select("SELECT * FROM user WHERE id = #{id} AND status = 1")
    User findById(@Param("id") Integer id);

    /**
     * 新增用户
     * @param user 用户对象
     * @return 影响行数
     */
    @Insert("INSERT INTO user (username, password, nickname, avatar, permission, status, create_time, update_time) " +
           "VALUES (#{username}, #{password}, #{nickname}, #{avatar}, #{permission}, #{status}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertUser(User user);

    /**
     * 更新用户
     * @param user 用户对象
     * @return 影响行数
     */
    @Update("UPDATE user SET nickname = #{nickname}, avatar = #{avatar}, permission = #{permission}, " +
           "status = #{status}, update_time = NOW() WHERE id = #{id}")
    int updateUser(User user);

    /**
     * 更新用户最后登录IP
     *
     * @param userId 用户ID
     * @param ip     IP地址
     */
    @Update("UPDATE user SET last_login_ip = #{ip}, update_time = NOW() WHERE id = #{userId}")
    void updateLastLoginIp(@Param("userId") Integer userId, @Param("ip") String ip);

    /**
     * 删除用户
     * @param id 用户ID
     * @return 影响行数
     */
    @Delete("DELETE FROM user WHERE id = #{id}")
    int deleteUser(@Param("id") Integer id);



    /**
     * 检查用户是否存在且状态正常
     * @param username 用户名
     * @return 用户是否存在
     */
    @Select("SELECT COUNT(*) > 0 FROM user WHERE username = #{username} AND status = 1")
    boolean existsByUsername(@Param("username") String username);

    /**
     * 根据用户名获取用户ID
     * @param username 用户名
     * @return 用户ID
     */
    @Select("SELECT id FROM user WHERE username = #{username} AND status = 1")
    Integer getUserIdByUsername(@Param("username") String username);
}
